package com.example.his.api.mis.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.his.api.mis.controller.form.InsertRoleForm;
import com.example.his.api.mis.controller.form.SearchRoleByPageForm;
import com.example.his.api.db.dao.RoleDao;
import com.example.his.api.db.pojo.RoleEntity;
import com.example.his.api.exception.HisException;
import com.example.his.api.mis.service.RoleService;
import com.example.his.api.utils.PageUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleDao, RoleEntity> implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Override
    public ArrayList<HashMap> searchAllRole() {
        return roleDao.searchAllRole();
    }

    @Override
    public PageUtils searchByPage(SearchRoleByPageForm form) {
        Page<HashMap<String,Object>> page = PageHelper.startPage(form.getPage(), form.getLength())
                .doSelectPage(() -> baseMapper.searchByPage(form.getRoleName()));
        return new PageUtils(page.getResult(), page.getTotal(),form.getPage(), form.getLength());
    }

    @Override
    public int insert(InsertRoleForm form) {
        RoleEntity roleEntity = BeanUtil.toBean(form, RoleEntity.class);
        JSONArray array = JSONUtil.parseArray(form.getPermissions());
        roleEntity.setPermissions(array.toString());
        roleEntity.setSystemic(1);
//        return baseMapper.saveRole(roleEntity);
        return baseMapper.insert(roleEntity);//因为描述字段 desc 是mysql关键字所以保存时会报错 用@TableField(value = "`key`") 解决
    }

    @Override
    public HashMap searchById(int id) {
        HashMap map = roleDao.searchById(id);
        return map;
    }

    @Override
    public ArrayList<Integer> searchUserIdByRoleId(int roleId) {
        ArrayList<Integer> list = roleDao.searchUserIdByRoleId(roleId);
        return list;
    }

    @Override
    @Transactional
    public int update(RoleEntity role) {
        int rows = roleDao.update(role);
        return rows;
    }

    @Override
    @Transactional
    public int deleteByIds(Integer[] ids) {
        if (!roleDao.searchCanDelete(ids)) {
            throw new HisException("无法删除关联用户的角色");
        }
        int rows = roleDao.deleteByIds(ids);
        return rows;
    }


}
